package www.wxwnb.clerk.ui.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import www.wxwnb.clerk.R;
import www.wxwnb.clerk.adapter.ItemAdapter;
import www.wxwnb.clerk.base.BaseActivity;
import www.wxwnb.clerk.bean.LogBean;
import www.wxwnb.clerk.bean.QueryBean;
import www.wxwnb.clerk.ui.api.ApiServer;
import www.wxwnb.clerk.ui.api.MyRetrofit;
import www.wxwnb.clerk.utils.ActivityCollector;
import www.wxwnb.clerk.utils.BitmapUtil;
import www.wxwnb.clerk.utils.Customer;
import www.wxwnb.clerk.utils.UrlConnect;

import static android.R.id.list;
import static www.wxwnb.clerk.R.id.line_check_sm;
import static www.wxwnb.clerk.R.id.line_notice_sm;
import static www.wxwnb.clerk.R.id.line_open_sm;
import static www.wxwnb.clerk.base.BaseFragment.JSON_RETURN_CODE;
import static www.wxwnb.clerk.base.BaseFragment.RETURN_CODE;

/**
 * afdkajfas nihao  xia ban la
 */
public class MainActivity extends BaseActivity  {

    private static final int TAKE_PHOTO = 1;
    public static final int PHOTOS = 2;
    private ImageView im_side_include;
    private SlidingMenu menu;
    private EditText ed_name_main;
    private EditText ed_pwd_main;
    private EditText ed_user_main;
    private EditText ed_phone_main;
    long beginTime = 0;
    private EditText ed_address_main;
    private ImageView iv_card_img;
    private ImageView iv_phone_img;
    private ImageView iv_code_img;
    private Button but_commit_main;
    private EditText ed_money_main;
    private static final int MY_PERMISSIONS_WRITE_EXTERNAL = 1;
    private PopupWindow mPhotoPopup;
    private int tag = 0;
    private String pwd_s;
    private ImageView iv_down_main;
    private View mView;

    private int business_type=0;
    private TextView txt_type_main;
    private PopupWindow popupWindow;
    String pic1="";
    String pic2="";
    String pic3="";
    private int business_i=0;
    private TextView txt_bu_main;
    private HashMap<Integer,String> map_bus=null;
    private ArrayList<String> list_txt=null;
    private ArrayList<Integer> list_type=null;
    private AlertDialog dialog;
    private TextView txt_clerk;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mView = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main,null);
    }

    @Override
    protected void initView() {
        im_side_include = (ImageView) findViewById(R.id.im_side_include);
        im_side_include.setSelected(false);
        menu = new SlidingMenu(this);
        menu.setMode(SlidingMenu.LEFT);//设置侧滑的方向
        menu.setBehindOffset(260);
        menu.attachToActivity(MainActivity.this, SlidingMenu.SLIDING_CONTENT);
        menu.setMenu(R.layout.slidingmenu_layout);
        //开户查询
        menu.findViewById(line_open_sm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intentActivity(MainActivity.this, AccountOpenActivity.class);
            }
        });
        //业绩查询
        menu.findViewById(line_check_sm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intentActivity(MainActivity.this, MsgQueryActivity.class);
            }
        });
        //审核通知
        menu.findViewById(line_notice_sm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              intentActivity(MainActivity.this, ReviewActivity.class);

            }
        });
        //line_compile_sm编辑资料
        menu.findViewById(R.id.line_compile_sm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                intentActivity(MainActivity.this, EditDataActivity.class);
            }
        });
        menu.findViewById(R.id.but_back_sm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Customer.getInstance().clear();
                ActivityCollector.finishActivity();
                intentActivity(MainActivity.this,LogActivity.class);
                finish();
            }
        });
        txt_clerk = menu.findViewById(R.id.txt_clerk_sl);
        txt_clerk.setText(Customer.getInstance().getUserName());


        iv_down_main = (ImageView) findViewById(R.id.iv_down_main);
        ed_name_main = (EditText) findViewById(R.id.ed_name_main);

        ed_pwd_main = (EditText) findViewById(R.id.ed_pwd_main);

        ed_user_main = (EditText) findViewById(R.id.ed_user_main);

        ed_phone_main = (EditText) findViewById(R.id.ed_phone_main);

        txt_type_main = (TextView) findViewById(R.id.txt_type_main);

        ed_address_main = (EditText) findViewById(R.id.ed_address_main);

        iv_card_img = (ImageView) findViewById(R.id.iv_card_img);

        iv_phone_img = (ImageView) findViewById(R.id.iv_phone_img);

        iv_code_img = (ImageView) findViewById(R.id.iv_code_img);

        but_commit_main = (Button) findViewById(R.id.but_commit_main);
        ed_money_main = (EditText) findViewById(R.id.ed_money_main);
        txt_bu_main = (TextView) findViewById(R.id.txt_ub_main);
        getBusinessDatas();
    }

    @Override
    public void initListener() {
        ed_money_main.setOnClickListener(this);
        ed_name_main.setOnClickListener(this);
        ed_pwd_main.setOnClickListener(this);
        ed_user_main.setOnClickListener(this);
        ed_phone_main.setOnClickListener(this);
        im_side_include.setOnClickListener(this);
        but_commit_main.setOnClickListener(this);
        iv_code_img.setOnClickListener(this);
        iv_phone_img.setOnClickListener(this);
        iv_card_img.setOnClickListener(this);
        txt_bu_main.setOnClickListener(this);
        ed_address_main.setOnClickListener(this);
        txt_type_main.setOnClickListener(this);
        findViewById(R.id.iv_down_main).setOnClickListener(this);

    }

    @Override
    public void initData() {
    }

    @Override
    public void processClick(View v) {
        switch (v.getId()) {
            //侧滑联动
            case R.id.im_side_include:
             //   im_side_include.setSelected(true);
                menu.toggle();
                break;
            //提交
            case R.id.but_commit_main:
                submit();
                break;
            case R.id.iv_card_img:
                //上传图片
                tag=1;
                requestPermissExternalStorage();
                break;
            case R.id.iv_code_img:
                tag=2;
                requestPermissExternalStorage();
                break;
            case R.id.iv_phone_img:
                tag=3;
                requestPermissExternalStorage();
                break;
            //拍照片
            case R.id.but_cream:
                if (tag == 1) {
                    tag = 11;
                } else if (tag == 2) {
                    tag = 21;
                } else if (tag == 3) {
                    tag = 31;
                }
                useCamera();
                break;
            //获取相册
            case R.id.but_photos:
                if (tag == 1) {
                    tag = 12;
                } else if (tag == 2) {
                    tag = 22;
                } else if (tag == 3) {
                    tag = 32;
                }
                useAlbum();
                break;
            case R.id.iv_down_main:
                //弹框
                setPopWindow(R.layout.popup_business);
                break;
            case R.id.txt_bus_pop:
                business_type=1;
                txt_type_main.setText("运营商家");
                dialog.dismiss();
                break;
            case R.id.txt_one_pop:
                business_type=2;
                txt_type_main.setText("一星商家");
                dialog.dismiss();

                break;
            case R.id.txt_two_pop:
                business_type=3;
                txt_type_main.setText("二星商家");
                dialog.dismiss();
                break;
            case R.id.txt_three_pop:
                business_type=4;
                txt_type_main.setText("三星商家");
                dialog.dismiss();
                break;
            case R.id.txt_yu_pop:

                business_type=5;
                txt_type_main.setText("预存商家");
                dialog.dismiss();
                break;
            //商家类型
            case R.id.txt_type_main:
                setPopWindow(R.layout.popup_business);
                break;
             //上级商家
            case R.id.txt_ub_main:
                  setPopWindows(R.layout.popup_up);
                break;
        }
    }
    //设置弹框
    private void setPopWindow(int layout) {
        View popup_business=LayoutInflater.from(MainActivity.this).inflate(layout,null);
        AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.UploadDialog);
        dialog = builder.create();
        dialog.setView(popup_business);
        dialog.setCancelable(false);
         popup_business.findViewById(R.id.txt_bus_pop).setOnClickListener(this);
         popup_business.findViewById(R.id.txt_one_pop).setOnClickListener(this);
         popup_business.findViewById(R.id.txt_two_pop).setOnClickListener(this);
         popup_business.findViewById(R.id.txt_three_pop).setOnClickListener(this);
         popup_business.findViewById(R.id.txt_yu_pop).setOnClickListener(this);
        dialog.show();
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                backgroundAlpha(1.0f);
                dialog.dismiss();
            }
        });

    }
    private void setPopWindows(int layout) {
        final View popup_business=LayoutInflater.from(MainActivity.this).inflate(layout,null);
        AlertDialog.Builder builder = new AlertDialog.Builder(this,R.style.UploadDialog);
        final AlertDialog dialog = builder.create();
        dialog.setView(popup_business);
        dialog.setCancelable(false);
        final ListView listView= popup_business.findViewById(R.id.pop_up_list);
        listView.setAdapter(new ItemAdapter(MainActivity.this,list_txt));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                txt_bu_main.setText(list_txt.get(i));
                business_i=list_type.get(i);
                Log.i("pwd_sssss",business_i+"mmm"+list_type.get(i));
                dialog.dismiss();
            }
        });

        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                backgroundAlpha(1.0f);
                dialog.dismiss();
            }
        });
        dialog.show();
        Log.e("list_txts",list_txt.size()+"..");
        if(list_txt.size()==0){
            Log.e("list_txt",list_txt.size()+"..");
            dialog.dismiss();
            Toast.makeText(this, "网络异常，请稍后再试", Toast.LENGTH_SHORT).show();
        }
    }

    private void submit() {
        // validate
        String log_name = ed_name_main.getText().toString().trim();
        if (TextUtils.isEmpty(log_name)) {
            Toast.makeText(this, "登陆账号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        //设置密码
        String pwd = ed_pwd_main.getText().toString().trim();
        if(TextUtils.isEmpty(pwd)){
            List<String> results=genCodes(6,100);
            pwd_s = results.get(0);
        }

        String user_name = ed_user_main.getText().toString().trim();
        if (TextUtils.isEmpty(user_name)) {
            Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        String phone= ed_phone_main.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, "手机号码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        String txt_t = txt_type_main.getText().toString().trim();
        if (TextUtils.isEmpty(txt_t)) {
            Toast.makeText(this, "商家类型不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        String address = ed_address_main.getText().toString().trim();
        if (TextUtils.isEmpty(address)) {
            Toast.makeText(this, "地址不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        String monery = ed_money_main.getText().toString().trim();
        if (TextUtils.isEmpty(monery)) {
            Toast.makeText(this, "开户金额不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        double monery_s = Double.parseDouble(monery);

        String business = txt_bu_main.getText().toString().trim();
       // int business_i = Integer.parseInt(business);
        if (TextUtils.isEmpty(business)) {
            Toast.makeText(this, "上级商家不能为空", Toast.LENGTH_SHORT).show();
            return;
        }else{
            String jobNumber = Customer.getInstance().getJobNumber();
            //进行发送网络请
            if(pic1.equals("")||pic2.equals("")||pic3.equals("")){
                Toast.makeText(this, "图片不能为空，请选择图片", Toast.LENGTH_SHORT).show();
                return;
            }
            if(pwd_s!=null){
                Log.i("pwd_s",pwd_s+"..."+pwd+ "商家类型"+business_type+"上级商家"+business_i);
                sendRequest(log_name,pwd_s,user_name,business_type,phone,address,monery_s,pic1,pic2,business_i,jobNumber,pic3);
           }else{
                Log.i("pwd_sa",pwd_s+"..."+pwd+ "商家类型"+business_type+monery_s+""+pic1+pic2+pic3+jobNumber+address+user_name);
                sendRequest(log_name,pwd,user_name,business_type,phone,address,monery_s,pic1,pic2,business_i,jobNumber,pic3);

            }

        }
    }

    private void sendRequest(String log_name, String pwd, final String user_name, int type, String phone, String address, double money, String licenseImage, String otherImage, int parentChief, String jobNumber, String accountImage){
        showUploadProgressDialog();
        Flowable<LogBean> flowable = MyRetrofit.getIntence().getRetrofit(UrlConnect.BASE_URL).create(ApiServer.class).openAccount(log_name, pwd, user_name, type, phone, address, money, licenseImage, otherImage, parentChief, jobNumber, accountImage);
          flowable.subscribeOn(Schedulers.io())
           .observeOn(AndroidSchedulers.mainThread())
           .subscribeWith(new DisposableSubscriber<LogBean>() {
            @Override
            public void onNext(LogBean logBean) {
                Log.e("logBean", logBean.toString());
                Toast.makeText(MainActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                ed_address_main.setText("");
                txt_bu_main.setText("");
                ed_money_main.setText("");
                ed_phone_main.setText("");
                txt_type_main.setText("");
                ed_pwd_main.setText("");
                ed_user_main.setText("");
                ed_name_main.setText("");
                iv_card_img.setImageResource(R.drawable.business_license);
                iv_phone_img.setImageResource(R.drawable.signing_information);
                iv_code_img.setImageResource(R.drawable.transfer_records);
                dismissUploadProgressDialog();
            }

            @Override
            public void onError(Throwable t) {
                dismissUploadDialog();
                Toast.makeText(MainActivity.this, "网络异常，请稍后再试", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onComplete() {

            }
        });
    }
    //请求权限
    private void requestPermissExternalStorage() {
        int i = ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (i != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_WRITE_EXTERNAL);
        } else {
            showPhotoPopup(R.layout.popup_choose_photo);
        }
    }

    //拍照或者相册R.layout.popup_choose_photo
    private void showPhotoPopup(int layout) {
        View photoView = LayoutInflater.from(MainActivity.this).inflate(layout, null);
        mPhotoPopup = new PopupWindow(photoView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mPhotoPopup.setBackgroundDrawable(new ColorDrawable());
        mPhotoPopup.setOutsideTouchable(true);
        mPhotoPopup.setTouchable(true);
        mPhotoPopup.setFocusable(true);
        mPhotoPopup.setAnimationStyle(R.style.dialog_anim);
        mPhotoPopup.showAtLocation(mView, Gravity.BOTTOM, 0, 0);
        backgroundAlpha(0.6f);
        photoView.findViewById(R.id.but_cream).setOnClickListener(this);
        photoView.findViewById(R.id.but_photos).setOnClickListener(this);
        mPhotoPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1.0f);
            }
        });
    }
    private String mCurrentPhotoPath;
    Uri mFileUri;
    private void useCamera() {
        //指定调用系统相机拍照时图片的存储路径，其中指定了一个临时文件temp.jpg来存储
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            // 打开相机
            Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePhotoIntent.resolveActivity(getPackageManager()) != null) {
                File outputImage = new File(Environment.getExternalStorageDirectory(), "output_image.jpg");
                if (outputImage.exists()) {
                    outputImage.delete();
                }
                try {
                    outputImage.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mCurrentPhotoPath = outputImage.getAbsolutePath();

                if (Build.VERSION.SDK_INT >= 24) {
                    mFileUri = FileProvider.getUriForFile(MainActivity.this, "com.wxwnb.wnb.fileprovider666", outputImage);
                } else {
                    mFileUri = Uri.fromFile(outputImage);
                }
                takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
                startActivityForResult(takePhotoIntent, TAKE_PHOTO);
            }
        } else {
            // 不可用
            Toast.makeText(this, "内存不可用", Toast.LENGTH_SHORT).show();
        }
    }
    private void useAlbum() {
        Intent intent = new Intent("android.intent.action.PICK");
        intent.setType("image/*");
        startActivityForResult(intent, PHOTOS);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mPhotoPopup.isShowing()) {
            mPhotoPopup.dismiss();
        }
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                // 两种方式 获取拍好的图片
                case TAKE_PHOTO:
                    Bitmap bitmapCapture = BitmapUtil.decodeSampleBitmapFromPath(mCurrentPhotoPath, 100, 100);
                    if (tag == 11) {
                        iv_card_img.setImageBitmap(bitmapCapture);
                    } else if (tag == 21) {
                        iv_code_img.setImageBitmap(bitmapCapture);
                    } else if (tag == 31) {
                        iv_phone_img.setImageBitmap(bitmapCapture);
                    }

                  sendPicture(BitmapUtil.decodeSampleBitmapFromPath(mCurrentPhotoPath, 1000, 1000));
                    break;
                case PHOTOS:
                    //打开相册并选择照片，这个方式选择单张
                    // 获取返回的数据，这里是android自定义的Uri地址
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    // 获取选择照片的数据视图
                    Cursor cursor = MainActivity.this.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    // 从数据视图中获取已选择图片的路径
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    // 将图片显示到界面上
                    Bitmap bitmapPhotos = BitmapUtil.decodeSampleBitmapFromPath(picturePath, 100, 100);
                    if (tag == 12) {
                        iv_card_img.setImageBitmap(bitmapPhotos);
                    } else if (tag == 22) {
                        iv_code_img.setImageBitmap(bitmapPhotos);
                    } else if (tag == 32) {
                        iv_phone_img.setImageBitmap(bitmapPhotos);
                    }
                    sendPicture(BitmapUtil.decodeSampleBitmapFromPath(picturePath, 1000, 1000));
                    break;
                default:
                    break;
            }
        }

    }
    //上传图片
    private void sendPicture(Bitmap bitmap){
        showUploadProgressDialog();
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), System.currentTimeMillis() + ".jpg");//将要保存图片的路径
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);
            bos.flush();
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        OkHttpClient client = new OkHttpClient();
        //创建文件部分的请求体对象
        RequestBody fileRequestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        //创建总的请求体对象,包含普通键值对和文件数据
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", file.getName(), fileRequestBody)
                .build();
        Request request = new Request.Builder()
                .url(UrlConnect.UPLOAD_IMG)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
               runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "图片上传失败，请重新上传", Toast.LENGTH_SHORT).show();
                        dismissUploadProgressDialog();
                       /* if (tag == 11 || tag == 12) {
                            iv_card_img.setImageResource(R.drawable.id_card_positive);
                        } else if (tag == 21 || tag == 22) {
                            iv_phone_img.setImageResource(R.drawable.id_card_negative);
                        } else if (tag == 31 || tag == 32) {
                            iv_code_img.setImageResource(R.drawable.id_card_negative);
                        }*/
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    processPictureResponse(response.body().string());
                } else {
                     runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                         dismissUploadProgressDialog();
                        }
                    });
                }
            }
        });
    }

    private void processPictureResponse(final String string) {
             runOnUiThread(new Runnable() {
            @Override
            public void run() {
            dismissUploadProgressDialog();
                Log.i("xxxxstri",string);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(string);
                    int returnCode = jsonObject.getInt(JSON_RETURN_CODE);
                    if (returnCode == RETURN_CODE) {
                        String data = jsonObject.getString("data");
                        switch (tag) {
                            case 11:
                            case 12:
                                pic1 = data;
                                break;
                            case 21:
                            case 22:
                                pic2 = data;
                                break;
                            case 31:
                            case 32:
                                pic3 = data;
                                break;
                        }
                    } else {
                        Toast.makeText(MainActivity.this, "图片上传失败，请重新上传", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    public static List<String> genCodes(int length, long num){

        List<String> results=new ArrayList<String>();

        for(int j=0;j<num;j++){
            String val = "";

            Random random = new Random();
            for(int i = 0; i < length; i++)
            {
                String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字

                if("char".equalsIgnoreCase(charOrNum)) // 字符串
                {
                    int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; //取得大写字母还是小写字母
                    val += (char) (choice + random.nextInt(26));
                }
                else if("num".equalsIgnoreCase(charOrNum)) // 数字
                {
                    val += String.valueOf(random.nextInt(10));
                }
            }
            val=val.toLowerCase();
            if(results.contains(val)){
                continue;
            }else{
                results.add(val);
            }
        }
        return results;
    }
    private void getBusinessDatas(){
        map_bus=new HashMap<>();
        list_txt=new ArrayList<>();
        list_txt.add("万能保");
        list_type=new ArrayList<>();
        list_type.add(0);
        Flowable<QueryBean> flowable = MyRetrofit.getIntence().getRetrofit(UrlConnect.BASE_URL).create(ApiServer.class).queryBusiness();
        flowable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableSubscriber<QueryBean>() {
                    @Override
                    public void onNext(QueryBean queryBean) {
                        if(queryBean.getReturnCode()==1){
                            List<QueryBean.DataBean> list = queryBean.getData();
                            for (int i=0;i<list.size();i++){
                                int id = list.get(i).getId();
                                String loginName = list.get(i).getLoginName();
                                map_bus.put(id,loginName);
                                list_txt.add(loginName);
                                list_type.add(id);
                            }
                            Log.i("pwd_sssaaa",list_type.size()+"");

                        }
                    }
                    @Override
                    public void onError(Throwable t) {
                    Toast.makeText(MainActivity.this, "网络异常，请稍后再试", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
    public void exit() {
        //实现两次点击退出系统；
        if (System.currentTimeMillis() - beginTime > 2000) {
            Toast.makeText(this, "再点击一次退出系统", Toast.LENGTH_SHORT).show();
            beginTime = System.currentTimeMillis();
        }else {
            finish();
            System.exit(0);
        }
    }
}
